package com.xr.blog.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * description : 全局日志处理器
 *
 * @author 幸仁杰
 * @create 2020/6/24 15:47
 */
@Aspect
@Component
@Order(5)
public class GlobalLogHandler {

    private ThreadLocal<Long> startTime = new ThreadLocal<>();


    @Pointcut("execution(public * com.xr.blog.controller.*.*(..))")
    public void controllerLog() {
    }

    @Pointcut("execution(public * com.xr.blog.service..*.*(..))")
    public void serviceLog() {
    }

    @Before(value = "controllerLog()")
    public void doBefore(JoinPoint joinPoint) {
        startTime.set(System.currentTimeMillis());
        Signature signature = joinPoint.getSignature();
        Logger logger = LoggerFactory.getLogger(signature.getDeclaringType());
        logger.info(getRequestAttributes("请求API接口开始执行"));
        String methodName = signature.toString();
//        String simpleMethodName = methodName.substring(methodName.lastIndexOf(".") + 1);
        logger.info("请求方法:{}, 请求参数:{}", methodName, Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(value = "controllerLog()", returning = "result")
    public void doAfterReturning(JoinPoint joinPoint, Object result) {
        Signature signature = joinPoint.getSignature();
        Logger logger = LoggerFactory.getLogger(signature.getDeclaringType());
        logger.info("响应结果对象: " + result);
        logger.info(getRequestAttributes(String.format("请求API接口结束, 耗时:%d ms", System.currentTimeMillis() - startTime.get())));
    }

    private String getRequestAttributes(String msgContext) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String url = request.getRequestURL().toString();
            String method = request.getMethod();
            return String.format("==================================%s, %s请求 URL:%s==================================", msgContext, method, url);
        } else {
            return String.format("==================================%s==================================", msgContext);
        }
    }


//    @Around("serviceLog()")
//    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
//        Signature signature = joinPoint.getSignature();
//        Logger logger = LoggerFactory.getLogger(signature.getDeclaringType());
//        long startTimeMillis = System.currentTimeMillis();
//        String methodName = signature.toString();
////        String simpleMethodName = methodName.substring(methodName.lastIndexOf(".") + 1);
//        logger.info("----------------------------------请求方法开始:{}, 请求参数:{}----------------------------------", methodName, Arrays.toString(joinPoint.getArgs()));
//        Object result;
//        try {
//            result = joinPoint.proceed();
//        } catch (Throwable t) {
//            logger.error("----------------------------------请求方法结束:{}, 耗时:{} ms, 异常信息:{}----------------------------------", methodName, System.currentTimeMillis() - startTimeMillis, t.toString(), t);
//            return t;
//        }
//        logger.info("----------------------------------请求方法结束:{}, 耗时:{} ms, 响应结果:{}----------------------------------", methodName, System.currentTimeMillis() - startTimeMillis, result);
//        return result;
//    }

}
